﻿namespace Blaze.Editor.AssetValidators
{
    using System.Linq;
    using System.Text.RegularExpressions;
    using Build;
    using Framework;
    using UnityEditor;
    using UnityEngine;

    /// <summary>
    /// 游戏跨模块引用。
    /// </summary>
    public class GameCrossModuleReference : AssetValidator
    {
        public override void Check(Object asset)
        {
            var path = PathUtility.FormatSeperator(AssetDatabase.GetAssetPath(asset));
            var match = mRegex.Match(path);
            var game = match.Result("${game}");
            var dependencies = AssetDatabase.GetDependencies(path, false);
            foreach (var dependency in dependencies)
            {
                if (!BuildSettings.IsPackableAsset(dependency))
                    continue;
                if (dependency.Contains(game))
                    continue;
                if (mPrefixes.Any(prefix => dependency.StartsWith(prefix)))
                    continue;
                Logger.ErrorFormat("引用了不是该游戏的资源：" + dependency);
            }
        }

        public override bool Precheck(string assetPath)
        {
            return BuildSettings.IsBuiltinAssetReferencableAsset(assetPath)
                   && mRegex.IsMatch(assetPath);
        }

        private static readonly string[] mPrefixes =
        {
            "Assets/Resources(AssetBundle)",
            "Assets/Resources(Skin)",
            "Assets/TextMesh Pro",
            "Assets/Spine/spine-unity"
        };

        private static readonly Regex mRegex = new Regex(@"Resources\(Game\)/(?<game>\w+)/");
    }
}